package com.cuiweiyou.happypaint.ui;

import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.cuiweiyou.happypaint.R;
import com.cuiweiyou.happypaint.base.ExitAppActivity;
import com.cuiweiyou.happypaint.util.DateFormatUtil;
import com.cuiweiyou.happypaint.util.FileUtil;
import com.cuiweiyou.happypaint.util.GsonUtil;
import com.cuiweiyou.happypaint.util.SoundUtil;
import com.cuiweiyou.happypaint.view.ConfigManager;
import com.cuiweiyou.happypaint.view.DialogView;
import com.cuiweiyou.happypaint.view.PaintView;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends ExitAppActivity {

    @BindView(R.id.paintView)
    public PaintView paintView;

    @BindView(R.id.colorView)
    public View colorView;
    @BindView(R.id.colorContainerView)
    public View colorContainerView;
    @BindView(R.id.colorRedView)
    public View colorRedView;
    @BindView(R.id.colorBlueView)
    public View colorBlueView;
    @BindView(R.id.colorYellowView)
    public View colorYellowView;
    @BindView(R.id.colorGreenView)
    public View colorGreenView;
    @BindView(R.id.colorPurpleView)
    public View colorPurpleView;
    @BindView(R.id.colorBlackView)
    public View colorBlackView;
    @BindView(R.id.colorWhiteView)
    public View colorWhiteView;

    @BindView(R.id.pencilView)
    public View pencilView;
    @BindView(R.id.pencilContainerView)
    public View pencilContainerView;
    @BindView(R.id.pencilSize1View)
    public View pencilSize1View;
    @BindView(R.id.pencilSize2View)
    public View pencilSize2View;
    @BindView(R.id.pencilSize3View)
    public View pencilSize3View;
    @BindView(R.id.pencilSize4View)
    public View pencilSize4View;

    @BindView(R.id.shapeView)
    public View shapeView;
    @BindView(R.id.shapeContainerView)
    public View shapeContainerView;
    @BindView(R.id.shapeStraightLineView)
    public View shapeStraightLineView;
    @BindView(R.id.shapeLineView)
    public View shapeLineView;
    @BindView(R.id.shapeRectView)
    public View shapeRectView;
    @BindView(R.id.shapeArcView)
    public View shapeArcView;
    @BindView(R.id.shapeDeltaView)
    public View shapeDeltaView;
    @BindView(R.id.shapeStarView)
    public View shapeStarView;
    @BindView(R.id.shapeRectFillView)
    public View shapeRectFillView;
    @BindView(R.id.shapeArcFillView)
    public View shapeArcFillView;
    @BindView(R.id.shapeDeltaFillView)
    public View shapeDeltaFillView;
    @BindView(R.id.shapeStarFillView)
    public View shapeStarFillView;


    @BindView(R.id.textView)
    public View textView;
    @BindView(R.id.textContainerView)
    public View textContainerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        paintView.setOnPaintViewClickListener(listener);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        intent.putExtra("self", true);
        sendBroadcast(intent); // 屏蔽状态栏下拉
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (223 == requestCode && resultCode == 223) {
            String json = data.getStringExtra("json");
            if (null != json) {
                List<ShapeModel> shapes = paintView.getShapes();
                if (shapes.size() > 0) {
                    DialogView.showDialog(MainActivity.this, onSaveListener, "保存当前图画", json);
                } else {
                    drawOldShapes(json);
                }
            }
        }
    }

    @Override
    public void whenAppExit() {

    }

    @OnClick(R.id.backShapeView)
    public void onBackShapeViewClick() {
        SoundUtil.getInstance().play(this, R.raw.back_shape);
        View visibleView = setSelectsBarGone();
        if (null == visibleView) { // 如果有某个选择bar打开这，先关闭之
            paintView.back();
        } else {
            visibleView.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.clearView)
    public void onClearViewClick() {
        SoundUtil.getInstance().play(this, R.raw.clear);
        View visibleView = setSelectsBarGone();
        if (null == visibleView) {
            paintView.clear();
        } else {
            visibleView.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.saveView)
    public void onSaveViewClick() {
        View visibleView = setSelectsBarGone();
        if (null == visibleView) {
            saveCurrent();
        } else {
            visibleView.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.otherView)
    public void onOtherViewClick() {
        View visibleView = setSelectsBarGone();
        if (null == visibleView) {
            nextActivityForResultKeepCurrent(HistoryActivity.class, 223);
        } else {
            visibleView.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.colorView)
    public void onColorViewClick() {
        rotationYAnim(colorView);
        setSelectsBarVisible(colorContainerView, pencilContainerView, shapeContainerView, textContainerView);
    }

    @OnClick(R.id.pencilView)
    public void onPencilViewClick() {
        rotationYAnim(pencilView);
        setSelectsBarVisible(pencilContainerView, colorContainerView, shapeContainerView, textContainerView);
    }

    @OnClick(R.id.shapeView)
    public void onShapeViewClick() {
        rotationYAnim(shapeView);
        setSelectsBarVisible(shapeContainerView, pencilContainerView, colorContainerView, textContainerView);
    }

    @OnClick(R.id.textView)
    public void onTextViewClick() {
        rotationYAnim(textView);
        setSelectsBarVisible(textContainerView, shapeContainerView, pencilContainerView, colorContainerView);
    }

    @OnClick(R.id.colorRedView)
    public void onColorRedViewClick() {
        paintView.setColor(ConfigManager.COLOR_RED);
        setShapeVisibility(colorRedView, colorContainerView);
    }

    @OnClick(R.id.colorBlueView)
    public void onColorBlueViewClick() {
        paintView.setColor(ConfigManager.COLOR_BLUE);
        setShapeVisibility(colorBlueView, colorContainerView);
    }

    @OnClick(R.id.colorYellowView)
    public void onColorYellowViewClick() {
        paintView.setColor(ConfigManager.COLOR_YELLOW);
        setShapeVisibility(colorYellowView, colorContainerView);
    }

    @OnClick(R.id.colorGreenView)
    public void onColorGreenViewClick() {
        paintView.setColor(ConfigManager.COLOR_GREED);
        setShapeVisibility(colorGreenView, colorContainerView);
    }

    @OnClick(R.id.colorPurpleView)
    public void onColorPurpleViewClick() {
        paintView.setColor(ConfigManager.COLOR_PURPLE);
        setShapeVisibility(colorPurpleView, colorContainerView);
    }

    @OnClick(R.id.colorBlackView)
    public void onColorBlackViewClick() {
        paintView.setColor(ConfigManager.COLOR_BLACK);
        setShapeVisibility(colorBlackView, colorContainerView);
    }

    @OnClick(R.id.colorWhiteView)
    public void onColorWhiteViewClick() {
        paintView.setColor(ConfigManager.COLOR_WHRITE);
        setShapeVisibility(colorWhiteView, colorContainerView);
    }


    @OnClick(R.id.pencilSize1View)
    public void onPencilSize1ViewClick() {
        paintView.setSize(ConfigManager.PENCIL_SIZE_1);
        setShapeVisibility(pencilSize1View, pencilContainerView);
    }

    @OnClick(R.id.pencilSize2View)
    public void onPencilSize2ViewClick() {
        paintView.setSize(ConfigManager.PENCIL_SIZE_2);
        setShapeVisibility(pencilSize2View, pencilContainerView);
    }

    @OnClick(R.id.pencilSize3View)
    public void onPencilSize3ViewClick() {
        paintView.setSize(ConfigManager.PENCIL_SIZE_3);
        setShapeVisibility(pencilSize3View, pencilContainerView);
    }

    @OnClick(R.id.pencilSize4View)
    public void onPencilSize4ViewClick() {
        paintView.setSize(ConfigManager.PENCIL_SIZE_4);
        setShapeVisibility(pencilSize4View, pencilContainerView);
    }


    @OnClick(R.id.shapeStraightLineView)
    public void onShapeStraightLineViewClick() {
        paintView.drawShape(ConfigManager.SHAPE_STRAIGHT_LINE);
        setShapeVisibility(shapeStraightLineView, shapeContainerView);
    }

    @OnClick(R.id.shapeLineView)
    public void onShapeLineViewClick() {
        paintView.drawShape(ConfigManager.SHAPE_LINE);
        setShapeVisibility(shapeLineView, shapeContainerView);
    }

    @OnClick(R.id.shapeRectView)
    public void onShapeRectViewClick() {
        paintView.drawShape(ConfigManager.SHAPE_RECT);
        setShapeVisibility(shapeRectView, shapeContainerView);
    }

    @OnClick(R.id.shapeArcView)
    public void onShapeArcViewClick() {
        paintView.drawShape(ConfigManager.SHAPE_ARC);
        setShapeVisibility(shapeArcView, shapeContainerView);
    }

    @OnClick(R.id.shapeDeltaView)
    public void onShapeDeltaViewClick() {
        paintView.drawShape(ConfigManager.SHAPE_DELTA);
        setShapeVisibility(shapeDeltaView, shapeContainerView);
    }

    @OnClick(R.id.shapeStarView)
    public void onShapeStarViewClick() {
        paintView.drawShape(ConfigManager.SHAPE_STAR);
        setShapeVisibility(shapeStarView, shapeContainerView);
    }

    @OnClick(R.id.shapeRectFillView)
    public void onShapeRectFillViewClick() {
        paintView.drawShape(ConfigManager.SHAPE_RECT_FILL);
        setShapeVisibility(shapeRectFillView, shapeContainerView);
    }

    @OnClick(R.id.shapeArcFillView)
    public void onShapeArcFillViewClick() {
        paintView.drawShape(ConfigManager.SHAPE_ARC_FILL);
        setShapeVisibility(shapeArcFillView, shapeContainerView);
    }

    @OnClick(R.id.shapeDeltaFillView)
    public void onShapeDeltaFillViewClick() {
        paintView.drawShape(ConfigManager.SHAPE_DELTA_FILL);
        setShapeVisibility(shapeDeltaFillView, shapeContainerView);
    }

    @OnClick(R.id.shapeStarFillView)
    public void onShapeStarFillViewClick() {
        paintView.drawShape(ConfigManager.SHAPE_STAR_FILL);
        setShapeVisibility(shapeStarFillView, shapeContainerView);
    }

    @OnClick({R.id.text0View, R.id.text1View, R.id.text2View, R.id.text3View, R.id.text4View, R.id.text5View, R.id.text6View, R.id.text7View, R.id.text8View, R.id.text9View, //
            R.id.textAView, R.id.textBView, R.id.textCView, R.id.textDView, R.id.textEView, R.id.textFView, R.id.textGView, R.id.textHView, R.id.textIView, R.id.textJView, R.id.textKView, R.id.textLView, R.id.textMView, //
            R.id.textNView, R.id.textOView, R.id.textPView, R.id.textQView, R.id.textRView, R.id.textSView, R.id.textTView, R.id.textUView, R.id.textVView, R.id.textWView, R.id.textXView, R.id.textYView, R.id.textZView})
    public void onTextLetterViewClick(View view) {
        String tag = (String) view.getTag();
        paintView.drawTextShape(tag);
        setShapeVisibility(view.getId(), textContainerView);
    }

    private void saveCurrent() {
        List<ShapeModel> shapes = paintView.getShapes();
        if (shapes.size() < 1) {
            return;
        }

        String timestemp = DateFormatUtil.millis2yyyyMMddHHmmss(System.currentTimeMillis());

        // String fpath = getFilesDir().getAbsolutePath();                // /data/data/应用包/files/ 。卸载app会删除
        String fpath = getExternalFilesDir(null).getAbsolutePath(); // /外置存储路径/Android/data/应用包/files/ 。卸载app会删除

        String json = GsonUtil.listToJson(shapes);
        String jsonfile = fpath + "/" + timestemp + "=HAPPY_JSON.txt";
        FileUtil.saveText(new File(jsonfile), json);

        Bitmap bitmap = paintView.getBitmap();
        // String path = Environment.DIRECTORY_PICTURES + "/HAPPY_PIC"; // SD卡/下的图片目录，须权限
        String pngfile = fpath + "/" + timestemp + "=HAPPY_PIC.png";
        FileUtil.saveImage(bitmap, pngfile);

        Toast.makeText(this, "图片已经保存", Toast.LENGTH_SHORT).show();
    }

    private PaintView.OnPaintViewClickListener listener = new PaintView.OnPaintViewClickListener() {
        @Override
        public int onPaintViewClick() {
            int visibility1 = colorContainerView.getVisibility();
            int visibility2 = pencilContainerView.getVisibility();
            int visibility3 = shapeContainerView.getVisibility();
            int visibility4 = textContainerView.getVisibility();

            setSelectsBarGone();

            colorContainerView.setVisibility(View.GONE);
            pencilContainerView.setVisibility(View.GONE);
            shapeContainerView.setVisibility(View.GONE);
            textContainerView.setVisibility(View.GONE);

            if (View.VISIBLE == visibility1 || View.VISIBLE == visibility2 || View.VISIBLE == visibility3 || View.VISIBLE == visibility4) {
                return View.VISIBLE;
            }

            return View.GONE;
        }
    };

    private DialogView.OnSureListener onSaveListener = new DialogView.OnSureListener() {
        @Override
        public void onSure(Object obj) {
            saveCurrent(); // 保存当前绘制的图画
            drawOldShapes((String) obj);
        }

        @Override
        public void onNo(Object obj) {
            drawOldShapes((String) obj);
        }
    };

    private void drawOldShapes(String json) {
        List<ShapeModel> list = GsonUtil.jsonToList(ShapeModel.class, json);
        paintView.drawOldShapes(list);
    }

    // 把打开的选择bar动画关闭（未执行gone），并返回这个bar
    private View setSelectsBarGone() {
        View visibleView = null;
        View[] vs = new View[]{colorContainerView, pencilContainerView, shapeContainerView, textContainerView};
        for (View v : vs) {
            if (View.VISIBLE == v.getVisibility()) {
                visibleView = v;
                Animation out = AnimationUtils.loadAnimation(MainActivity.this, R.anim.anim_zoom_out_selects_bar_layout);
                v.startAnimation(out);
            }
        }

        return visibleView;
    }

    // 把某个选择bar动画打开（并visible），其它的选择bar直接gone关闭
    private void setSelectsBarVisible(View visibleView, View... goneViews) {
        for (View view : goneViews) {
            view.setVisibility(View.GONE);
        }

        Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_zoom_in_selects_bar_layout);
        visibleView.startAnimation(animation);
        visibleView.setVisibility(View.VISIBLE);
    }

    // 把选择item动画，再将其bar动画关闭（并gone）
    private void setShapeVisibility(int viewID, View goneView) {
        View viewById = findViewById(viewID);
        setShapeVisibility(viewById, goneView);
    }

    // 把选择item动画，再将其bar动画关闭（并gone）
    private void setShapeVisibility(View animView, View goneView) {
        Animation rotateIn = AnimationUtils.loadAnimation(this, R.anim.anim_rotate_in_shape_layout);
        Animation rotateOut = AnimationUtils.loadAnimation(this, R.anim.anim_rotate_out_shape_layout);

        rotateIn.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                animView.startAnimation(rotateOut);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });

        rotateOut.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                Animation out = AnimationUtils.loadAnimation(MainActivity.this, R.anim.anim_zoom_out_selects_bar_layout);
                goneView.startAnimation(out);
                goneView.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });

        animView.startAnimation(rotateIn);
    }

    private void rotationYAnim(View view){
        ValueAnimator animator = ValueAnimator.ofFloat(0, 360);
        animator.setDuration(400);
        animator.setInterpolator(new AccelerateInterpolator());
        animator.setRepeatCount(2);
        animator.setRepeatMode(ValueAnimator.REVERSE); // 动画正序完成后，倒回去
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float rotate = (float)valueAnimator.getAnimatedValue();
                view.setRotationY(rotate);
            }
        });
        animator.start();
    }
}
